package cn.s1995.sloth.bizs.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.s1995.sloth.common.core.constant.enums.hint.Hint;
import cn.s1995.sloth.bizs.entity.ProdProp;
import cn.s1995.sloth.bizs.entity.ProdPropValue;
import cn.s1995.sloth.bizs.mapper.ProdPropMapper;
import cn.s1995.sloth.bizs.oo.dto.ProdPropDTO;
import cn.s1995.sloth.bizs.service.ProdPropService;
import cn.s1995.sloth.bizs.service.ProdPropValueService;
import cn.s1995.sloth.common.core.util.R;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

/**
 * 产品属性
 *
 * @author Lex
 * @date 2023-12-15 00:51:46
 */
@Service
public class ProdPropServiceImpl extends ServiceImpl<ProdPropMapper, ProdProp> implements ProdPropService {

    @Resource
    private ProdPropValueService prodPropValueService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveSpec(ProdPropDTO req) {
        long count = this.count(
                Wrappers.lambdaQuery(ProdProp.class)
                        .eq(ProdProp::getRule, req.getRule())
                        .eq(ProdProp::getPropName, req.getPropName())

        );
        if (count > 0) {
            return R.failed(Hint.BMS_PROD_PROP_ALREADY_EXISTS);
        }
        this.save(req);

        if (CollUtil.isNotEmpty(req.getProdPropValueList())) {
            // 保存规格值
            prodPropValueService.saveBatch(req.getProdPropValueList());
        }

        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R removeSpes(ArrayList<Long> ids) {
        // 删除规格
        baseMapper.deleteBatchIds(ids);
        // 删除规格值
        prodPropValueService.remove(Wrappers.<ProdPropValue>lambdaQuery().in(ProdPropValue::getPropId, ids));
        return R.ok();
    }
}
